package kayao.server.network.message;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Vector;

import kayao.common.Client;
import kayao.common.KayaoValues;
import kayao.common.NetworkUtils;
import kayao.server.AreaManager;
import kayao.server.DesktopServer;

public class KingsRequestMessage extends Message {

	protected byte []mDataReceived;
	protected KingsRequestMessage(IncomingMessage m) {
		super(m.getIp(), 3, 4000, 0);
		mDataReceived=m.getData();
		createPacketData();
	}

	@Override
	public void createPacketData() {
		byte []value=new byte[4];
		//get the counter
		System.arraycopy(mDataReceived, 5, value, 0, 4);
		int counter = NetworkUtils.insertByteArrayToInt(mDataReceived, 5);

		//get the id (int32)
		System.arraycopy(mDataReceived, 9, value, 0, 4);
		int id = NetworkUtils.insertByteArrayToInt(mDataReceived, 9);

		//get the number of requests (one byte)
		System.arraycopy(mDataReceived, 13, value, 0, 1);
		int number = NetworkUtils.unsignedByteToInt(value[0]);
		
		// Create the array with data to send
		//The method calculate size DOES the update of the kings
		//It's needed to be done before create the answer because of its size
		mSendData = new byte[calculateSize(id,number)];//10 + (10+length) * number

		int index=0;
		//coping the magic number (already checked)
		System.arraycopy(mDataReceived, 0, mSendData, index, 4);
		index+=4;
		//id message
		mSendData[index] = KayaoValues.KING_REQUEST_REPLY_MESSAGE;
		index++;
		//counter
		NetworkUtils.insertIntToByteArray(mSendData, index, counter);
		index+=4;
		
		//copying the number of requests to send too
		mSendData[index]=(byte)number;
		index++;

		//get the requests
		int kingid,kingdom;
		int index2=14;
		
		for(int i=0;i<number;i++)
		{
			//get the kingdom in value
			System.arraycopy(mDataReceived, index2, value, 0, 1);
			//increase the reading index
			index2++; 
			//transform it to an integer
			kingdom=NetworkUtils.unsignedByteToInt(value[0]);
			//get the king WITHOUT MODIFY IT
			kingid=AreaManager.getKingByRegion(kingdom);
			System.out.println("[KingRequestMessage] - Applicant ID:"+ id + ", Kingdom: " + kingdom+", KingID: "+ kingid);
			//write its mSendData
			if(kingid==0)
			{
				NetworkUtils.insertIntToByteArray(mSendData,index,0);
				index+=4;
			} 
			else 
			{
				//id+teamid+length+name+ip
				Client c=DesktopServer.getClient(kingid);
				NetworkUtils.insertIntToByteArray(mSendData, index, c.getId());
				index+=4;
				mSendData[index]=(byte)c.getTeam();
				index++;
				//length
//				System.out.println("[KingsRequestMessage] length: "+c.getName().length()+" name: "+c.getName());
				mSendData[index]=(byte)c.getName().length();
				index++;
				//name
				for(int j=0; j<c.getName().length();j++)
				{
					mSendData[index]=(byte) c.getName().charAt(j);
					index++;
				}
				//ip
				try {
					System.arraycopy(InetAddress.getByName(c.getIP()).getAddress(), 0, mSendData, index, 4);
					index+=4;
				} catch (UnknownHostException e) {
					System.out.println("[KingRequest] - Error creating ip of teammate");
				}
			}
		}
	}

	@Override
	public String type() {
		return "KingRequest";
	}
	private int calculateSize(int id, int number) {
		byte value[]=new byte[4];
		int size=10;
		int region=0;
		AreaManager.deleteKingById(id);
		//10 + (10+length) * number
		int index=14;
		Vector<Integer> regions=new Vector<Integer>();
		for(int i=0;i<number;i++)
		{
			//get kingdom in value
			System.arraycopy(mDataReceived, index, value, 0, 1);
			index++;
			//the first kingdom will be its region
			if(i==0)region=NetworkUtils.unsignedByteToInt(value[0]);
			//convert the kingdom
			int kingdom=NetworkUtils.unsignedByteToInt(value[0]);
			regions.add(kingdom);
			//Check out the king. Change if it's needed
			int kingid=AreaManager.checkKing(id, region, kingdom);
			//Increase the size depending of the result of the checkKing
			if(kingid==0)size+=4;
			else//id+teamid+length+name+ip
				size+=(4+1+1+4+DesktopServer.getClient(kingid).getName().length());
		}
		//System.out.println("[KingRequest] - Size: " + size);
		AreaManager.removeInterestInRegions(id,regions);
		return size;
	}	


}
